﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel.Syndication;
using System.Web.Http;
using System.Xml;
using Cofe.Core;
using Cofe.Core.Filter;
using Cofe.Core.Implements;
using Cofe.Core.Logger;
using Cofe.Core.Utils;
using Cofe.Data;
using Cofe.Web.Feed;
using Cofe.Web.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Cofe.Web.Controllers.Api
{
    public class EventsController : ApiController
    {

        [HttpGet]
        [Authorize]
        public HttpResponseMessage GetEvent(int page)
        {
            var feed = CofeWsServices.Feeds.GetFeedService<CofeSystemEventArgs>().Repository.GetFeed(
                FeedId.FromId(page, FeedType.ArchiveFeed));

            if (feed == null || !feed.IsExists)
            {
                feed = CofeWsServices.Feeds.GetFeedService<CofeSystemEventArgs>().Repository.GetRecentFeed();
                if (feed == null || feed.FeedId.Id != page)                    
                    return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return CofeWsServices.HttpMessageFormatter.CreateResponse(Request, feed, null, new ResponseFormatterInfo()
            {
                StatusCode = HttpStatusCode.OK,
                MaxAge = TimeSpan.FromDays(15),
                ETag = feed.ETag
            });
        }


        [HttpGet]
        [Authorize]
        public HttpResponseMessage GetFeed()
        {
            var feed = CofeWsServices.Feeds.GetFeedService<CofeSystemEventArgs>().Repository.GetRecentFeed();
             if (feed == null || !feed.IsExists)
                 return new HttpResponseMessage(HttpStatusCode.NotFound);


            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            string urlPath = Url.Route("DefaultApi", new
            {
                httproute = ""                
            }) + "?page=" + feed.FeedId.Id.ToString();
            response.Headers.Location = UrlUtils.FormatUri(urlPath);
            return response;
        }

        [HttpGet]
        [Authorize]
        public HttpResponseMessage GetEvent(Guid id)
        {
            var eventItem = CofeWsServices.Feeds.GetFeedService<CofeSystemEventArgs>().Repository.GetEvent(
                id);

            if (eventItem == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            return CofeWsServices.HttpMessageFormatter.CreateResponse(Request, eventItem, null, new ResponseFormatterInfo()
            {
                StatusCode = HttpStatusCode.OK,
                MaxAge = TimeSpan.FromDays(15)
            });
        }
        
    }
}
